package com.mqz.zebraEcommerce.commodity.service.impl;

import com.mqz.zebraEcommerce.commodity.entity.*;
import com.mqz.zebraEcommerce.commodity.service.*;
import com.mqz.zebraEcommerce.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mqz.zebraEcommerce.common.utils.PageUtils;
import com.mqz.zebraEcommerce.common.utils.Query;

import com.mqz.zebraEcommerce.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    private String DEFAULT_IMG = "https://zebra-ecommerce.oss-cn-hangzhou.aliyuncs.com/test.jpg";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        //处理查询
        String key = (String) params.get("key");
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();

        if (StringUtils.isNotBlank(key)) {
            wrapper.and(wp -> {
                wp.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !brandId.equalsIgnoreCase("0")) {
            wrapper.eq("brand_id", brandId);
        }

        String catalogId = (String) params.get("catalogId");
        if (StringUtils.isNotBlank(catalogId) && !catalogId.equalsIgnoreCase("0")) {
            wrapper.eq("catalog_id", catalogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductBaseAttrValueService productBaseAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    ProductSaleAttrValueService productSaleAttrValueService;

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //保存spu图片集
        List<String> description = spuSaveVO.getDescription();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        if (description == null || description.size() == 0) {
            spuInfoDescEntity.setDescription(DEFAULT_IMG);
        } else {
            spuInfoDescEntity.setDescription(String.join(",", description));
        }
        spuInfoDescService.save(spuInfoDescEntity);
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //保存商品SPU基本属性信息
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductBaseAttrValueEntity> productBaseAttrValueEntities = baseAttrs.stream().map(baseAttr -> {

            ProductBaseAttrValueEntity productBaseAttrValueEntity = new ProductBaseAttrValueEntity();

            productBaseAttrValueEntity.setAttrId(baseAttr.getAttrId());
            AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
            productBaseAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productBaseAttrValueEntity.setAttrSort(0);
            productBaseAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productBaseAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            productBaseAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productBaseAttrValueEntity;
        }).collect(Collectors.toList());
        productBaseAttrValueService.saveBatch(productBaseAttrValueEntities);

        //保存商品SKU信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setPrice(sku.getPrice());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuName(sku.getSkuName());
                skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
                skuInfoEntity.setSkuTitle(sku.getSkuTitle());

                String defaultImg = DEFAULT_IMG;
                for (Images skuImages : sku.getImages()) {
                    if (skuImages.getDefaultImg() == 1) {
                        defaultImg = skuImages.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoService.save(skuInfoEntity);

                //保存商品SKU图片集
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter(image -> {
                    return StringUtils.isNotBlank(image.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //保存商品SKU销售属性信息
                List<Attr> attrs = sku.getAttr();
                List<ProductSaleAttrValueEntity> productSaleAttrValueEntities = attrs.stream().map(attr -> {
                    ProductSaleAttrValueEntity productSaleAttrValueEntity = new ProductSaleAttrValueEntity();
                    productSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    productSaleAttrValueEntity.setAttrId(attr.getAttrId());
                    productSaleAttrValueEntity.setAttrName(attr.getAttrName());
                    productSaleAttrValueEntity.setAttrSort(0);
                    productSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                    return productSaleAttrValueEntity;
                }).collect(Collectors.toList());
                productSaleAttrValueService.saveBatch(productSaleAttrValueEntities);


            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    @Override
    public void up(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 1);
    }

    @Override
    public void down(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 2);
    }
}